<template>
  <div class="container">
    <div ref="contentContainer" class="content-container">
      <div ref="content">
        <InfiniteLoading direction="top" @infinite="loadMoreHistory">
          <template #no-more>
            <div class="message-prompt">没有更多消息了</div>
          </template>
          <template #no-results>
            <div class="message-prompt">没有更多消息了</div>
          </template>
        </InfiniteLoading>
        <div v-for="(message, index) in messages">
          <div v-if="isShowTimes[index]" class="message-prompt">
            {{ message.sendtime | according-to-now }}
          </div>
          <div :style="{ flexDirection: message.direction === 'received' ? 'row' : 'row-reverse' }"
            class="message-cell" >
            <van-image :src="message.direction === 'received' ? targetAvatar : sourceAvatar" height="32"
              width="32" />
            <van-button round size="small" type="default">{{ message.content }}</van-button>
          </div>
        </div>

      </div>
    </div>
    <div class="footer" style="margin-bottom: 1px">
      <el-input v-model="typingText" border placeholder="输入内容" style="float: left;width: 88%;" ></el-input>
      <el-button size="small" style="float: right;width: 10%;height: 35px"  type="success" @click="sendText">发送</el-button>
    </div>
  </div>
</template>

<script>
import zhCode from 'date-fns/locale/zh-CN'
import format from 'date-fns/format'
import formatDistance from 'date-fns/formatDistance'
import differenceInMinutes from 'date-fns/differenceInMinutes'
import differenceInYears from 'date-fns/differenceInYears'
import isSameDay from 'date-fns/isSameDay'

import InfiniteLoading from 'vue-infinite-loading'
import VanButton from 'vant/lib/button'
import 'vant/lib/button/style'
import VanImage from 'vant/lib/image'
import 'vant/lib/image/style'
import VanField from 'vant/lib/field'
import 'vant/lib/field/style'
import {cmsGetListHistory} from "@/api/cms/chat";

export default {
  name: 'Chat',
  components: {
    InfiniteLoading,
    'van-button': VanButton,
    'van-image': VanImage,
    'van-field': VanField
  },
  filters: {
    accordingToNow (date) {
      date = date instanceof Date ? date : new Date(date)
      const now = new Date()

      if (differenceInMinutes(now, date) <= 30) {
        return formatDistance(new Date(date), now, { locale: zhCode, addSuffix: true })
      } else if (isSameDay(now, date)) {
        return format(date, 'p', { locale: zhCode })
      } else if (differenceInYears(now, date) < 1) {
        return format(date, 'MMM do p', { locale: zhCode })
      } else {
        return format(date, 'PPP p', { locale: zhCode })
      }
    }
  },
  props: {
    loadHistory: {
      type: Function,
      default () {
        return { messages: [], hasMore: false }
      }
    },
    sendMessage: {
      type: Function,
      default ({ content }) {
        return { content, direction: 'sent' }
      }
    }
  },
  data () {
    return {
      data:[],
      messages: [

      ],
      sourceAvatar: "",
      targetAvatar: "",
      typingText: '',
      scrolledToBottom: false,
      friendId:0
    }
  },

  computed: {
    isShowTimes () {
      let lastTime = new Date(0)
      return this.messages.map(message => {
        const messageTime = message.time instanceof Date ? message.sendtime : new Date(message.sendtime)

        if (differenceInMinutes(messageTime, lastTime) > 10) {
          lastTime = messageTime
          return true
        } else {
          return false
        }
      })
    },




  },
  created() {
    this.getHistory();

    this.$bus.$on("initialization",row => {
      this.getHistory()
    })
    this.$bus.$on("exchangeFriend",row => {
      this.typingText='';
      this.friendId=row.userId;
      this.targetAvatar = "http://localhost:8080"+row.avatar
      let avatar =  this.$store.state.user.avatar
      this.sourceAvatar = "http://localhost:8080"+avatar.substring("/dev-api".length)

      this.getHistory()
    })
    this.$bus.$on("handleMessage",message => {
      const msg= {time: this.getCurrentTimeHHMM(),message:message}
      this.$bus.$emit('sendText',msg)
      if (message.fromUsername == this.friendId ){
        this.messages.push({fromUsername:message.fromUsername, targetUsername:message.targetUsername,content: message.content, time: new Date(), direction: 'received'})
      }
    })
  },
  methods: {
    getHistory(){
      cmsGetListHistory({fromUsername:this.$store.state.user.id,targetUsername:this.friendId}).then(res =>{
        this.messages=res.data;
        this.getDirection(this.messages)
      })
    },
    getDirection(msg){
      for (var i=0;i<msg.length;i++)
      if (msg[i].fromUsername == this.$store.state.user.id){
        this.messages[i].direction='sent'
      }else {
        this.messages[i].direction='received'
      }
    },
    getCurrentTimeHHMM() {
    const now = new Date();
    const hour = now.getHours().toString().padStart(2, '0');
    const minute = now.getMinutes().toString().padStart(2, '0');
    return `${hour}:${minute}`;
    },

    sendText () {
      if (this.friendId === 0){
        alert("请先选择聊天好友")
        this.typingText='';
      }else if (this.typingText!=''){
        const sendtime= new Date();
        const message = this.sendMessage({ content: this.typingText,targetUsername: this.friendId,fromUsername:this.$store.state.user.id,sendtime: sendtime.toString()})
        this.typingText = ''
        if (message instanceof Promise) {
          message.then(
            message => this.appendNew(
                Object.assign({ sendtime: new Date(), direction: 'sent' }, message)
            )
          ).catch(e => console.error('发送消息出错', e))
        } else {
          this.appendNew(Object.assign({ sendtime: new Date(), direction: 'sent' }, message))
        }
        message.fromUsername = message.targetUsername
        const msg= {time: this.getCurrentTimeHHMM(),message:message}
        this.$bus.$emit('sendText',msg)

      }

    },
    prependHistory (history, $state) {
      const messages = history.messages || []
      // messages 以逆序排列
      this.messages.unshift(...messages.reverse())
      history.hasMore ? $state.loaded() : $state.complete()

      this.$nextTick(() => {
        if (this.scrolledBarVisible) return

        if (this.$refs.content.clientHeight > this.$refs.contentContainer.clientHeight) {
          this.scrollToBottom()
          this.scrolledToBottom = true
        }
      })
    },
    appendNew (...messages) {
      messages = messages.map(message => Object.assign({ direction: 'received' }, message))
      this.messages.push(...messages)
      this.data.push(...messages)
      localStorage.setItem('data', JSON.stringify(this.data));
      this.$nextTick(this.scrollToBottom)
    },
    loadMoreHistory ($state) {
      const history = this.loadHistory()
      if (history instanceof Promise) {
        history.then(history => {
          this.prependHistory(history, $state)
        }).catch(e => {
          console.error('加载历史消息出错', e)
        })
      } else {
        this.prependHistory(history, $state)
      }
    },
    scrollToBottom () {
      this.$refs.contentContainer.scrollTop = Number.MAX_SAFE_INTEGER
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background-color: rgba(255, 255, 255, 0);
  display: flex;
  flex-direction: column;
  height: 93%;

  .content-container {
    flex-grow: 1;
    overflow-y: auto;
  }

  .footer {
    height: 50px;
  }
}

.message-cell {
  display: flex;
  padding: 2px;
  margin-bottom: 2px;

  > * {
    margin: 2px;
  }
}

.message-prompt {
  text-align: center;
  color: #969799;
  font-size: 14px;
  line-height: 24px;
}
</style>
